import { Injectable, ExecutionContext, CanActivate, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY_METADATA } from '../../common/contants/decorator.contant';
import { User } from '../../entities/user.entity';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 获取路由需要的角色
    const requiredRoles = this.reflector.getAllAndOverride<number[]>(ROLES_KEY_METADATA, [
      context.getHandler(),
      context.getClass(),
    ]);

    // 如果没有设置需要的角色，则默认允许访问
    if (!requiredRoles || requiredRoles.length === 0) {
      return true;
    }

    // 获取当前用户
    const request = context.switchToHttp().getRequest();
    const user = request.user.user;
    // console.log('管理员校验权限: user :', user.user);
    // 检查用户是否存在
    if (!user) {
      throw new ForbiddenException('用户未登录');
    }

    // 检查用户角色是否满足要求
    const hasRequiredRole = requiredRoles.includes(user.role);

    if (!hasRequiredRole) {
      throw new ForbiddenException('权限不足，需要管理员权限');
    }

    return true;
  }
}
